package bin_tree.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * 借助栈来实现前序遍历 方法2
 **/
public class Num144_2 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            // 先访问根节点
            ret.add(cur.val);
            // 先压入右孩子
            if (cur.right != null) {
                stack.push(cur.right);
            }
            // 再压入左孩子
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
        return ret;
    }
}